<template>
  <el-col :span="16" class="basicInfo">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" >
          <el-form-item prop="name" label="活动名称">
            <el-col :span="17">
              <el-input v-model.trim="form.name" placeholder="请输入内容" :disabled="alreadyReleased"></el-input>
            </el-col>
          </el-form-item>


          <el-form-item prop="imageUrl" label="图片地址">
            <el-col :span="17">
                 <el-input v-model="form.imageUrl" placeholder="请输入内容" :disabled="alreadyReleased"></el-input>
            </el-col>
            <el-col :span="17">
              <el-upload
                :name='uploadConfig.name'
                :action="uploadConfig.uploadeUrl"
                :multiple="false"
                :accept="uploadConfig.accept"
                :show-file-list='false'
                :http-request='submitUpload'
                :before-upload='handleBeforeUpload'
                :file-list="fileList">
                <el-button size="small" type="primary">图片上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif文件，且不超过5M</div>
              </el-upload>
            </el-col>
          </el-form-item>

          <el-form-item label="是否分享" style="text-align: left;">
            <template>
              <el-radio class="radio" v-model="form.shared" label="YES" :disabled="alreadyReleased">是</el-radio>
              <el-radio class="radio" v-model="form.shared" label="NO"  :disabled="alreadyReleased">否</el-radio>
            </template>
          </el-form-item>
          <el-row class="actDateTime">
              <el-col :span="24" >
                  <el-form-item  prop="dateStart" :rules="[{ required: true, message: '请输入开始时间', trigger: 'blur' },]" label="活动时间" style="display: inline-block;float: left;">
                    <el-date-picker v-model="dateStart" type="datetime" placeholder="选择开始时间" :disabled="alreadyReleased"></el-date-picker>
                  </el-form-item>
                  <el-form-item  prop="dateEnd" label="~" :rules="[{ required: true, message: '请输入开始时间', trigger: 'blur' },]" style="float: left;">
                    <el-date-picker v-model="dateEnd" type="datetime" placeholder="选择结束时间" :disabled="alreadyReleased" ></el-date-picker>
                  </el-form-item>
              </el-col>
          </el-row>
          <el-form-item prop="url" label="活动url">
              <el-col :span="17">
                  <el-input v-model="form.url" placeholder="请输入内容" :disabled="alreadyReleased"></el-input>
              </el-col>
          </el-form-item>
          <el-form-item prop="remark" label="活动描述">
            <el-col :span="17">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 4}"
                  placeholder="请输入内容"
                  v-model.trim="form.remark" :disabled="alreadyReleased">
                </el-input>
            </el-col>
          </el-form-item>
      <div style="float: left;margin-top:20px;">
      <el-row v-if="pageType=='create'?true:false">
        <el-button @click="prev" class="buttonStep">上一步</el-button>
        <el-button @click="submit('form')" v-if="createActivity" class="buttonStep">完成</el-button>
        <el-button @click="NextStep('form')" v-else class="buttonStep">下一步</el-button>
      </el-row>
      <el-row v-else>
        <el-button @click="NextStepEdit('form')" class="buttonStep saveButton">保存</el-button>
      </el-row>
      </div>
    </el-form>
  </el-col>
</template>

<script>
  import browserMD5File from 'browser-md5-file'
  import moment from 'moment';
  import { api, postUploadImg } from 'api/common'
  import {formRules, activityStatus} from './config.js'
  import {postLog} from 'api/common/index.js'
  export default{
    props: ['CheckInfo', 'pageType'], //checkInfo为编辑页传入的数据，pageType为页面类型
    data () {
      return {
        createActivity: false, //创建或保存活动
        alreadyReleased: false, //是否可编辑
        dateStart: '',
        dateEnd: '',
        uploadConfig: {//上传图片用的配置
          name: 'upload_file',
          uploadeUrl: api.postUploadImg, //图片上传的链接
          accept: 'image/png,image/gif,image/jpeg,image/jpg'
        },
        file_md5: '',
        form: {//提交的表单
          creator: sessionStorage.getItem('realName'),              //创建人
          type: '',                                                //活动类型
          name: '',                                                //活动名称
          imageUrl: '',                                            //图片url
          status: 'WARM_UP',                                       //是否开始
          shared: 'YES',                                           //是否分享
          url: '',                                                 //活动url
          remark: '',                                              //活动描述
          dateStart: '',                                           //活动开始时间
          dateEnd: ''                                              //活动结束时间
        },
        fileList: [], //上传图片列表
        rules: formRules, //验证规则
        activityStatus: activityStatus//活动状态
      }
    },
    watch: {
      //监听编辑页面ajax传入的数据变化,只有编辑页面才会传入这个参数
      CheckInfo (val, oldval) {
        this.form.id = val.id;
        this.form.type = val.type;
        this.form.name = val.name;
        this.form.name = val.name;
        this.form.imageUrl = val.imageUrl;
        this.form.status = val.status;
        this.form.shared = val.shared;
        this.form.url = val.url;
        this.form.remark = val.remark;
        this.dateStart = val.dateStart;
        this.dateEnd = val.dateEnd;
        console.log(val)
      },
      dateStart (val, oldval) {
        this.form.dateStart = moment(val).format('YYYY-MM-DD HH:mm:ss')
      },
      dateEnd (val, oldval) {
        this.form.dateEnd = moment(val).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    computed: {
    },
    methods: {
      handleBeforeUpload (file) { //文件上传前
        // console.log('handleBeforeUpload', file)
        const isLt3M = file.size / 1024 / 1024 < 5;
        if (!isLt3M) {
          this.$message.error('上传图片大小不能超过 5MB!');
        }
        return isLt3M
      },
      submitUpload (obj) {
        console.log(obj);
        let file = obj.file
        // console.warn('submitUpload', file)
        browserMD5File(file, (err, md5) => {
          let fd = new FormData()
          fd.append('upload_file', file)
          fd.append('file_md5', md5)
          this.postUploadImg(fd)
        });
      },
      async postUploadImg (fd) {
        try {
          let back = await postUploadImg(fd)
          back = back.data
          console.log('postUploadImg', back)
          if (back.success) {
            this.form.imageUrl = back.file_path
          } else {
            this.$alert('图片上传失败');
          }
        } catch (err) {
          this.$alert('图片上传失败');
          console.error(err)
        }
      },
      NextStep (form) { //提交基本信息,新增页面
        this.$refs[form].validate((valid) => {
          if (valid) {
            let timeCheck = this.compTime(this.form.dateStart, this.form.dateEnd);//开始日期和结束日期验证
            if (timeCheck == 'exception') {
              this.$emit('getInfoData', {basicInfoFrom: this.form, showModules: 'coupon', active: 3});//导航进度条前进一步
            }
          } else {
            return false;
          }
        });
      },
      submit (form) { //推广活动直接创建
        this.$refs[form].validate((valid) => {
          if (valid) {
            let timeCheck = this.compTime(this.form.dateStart, this.form.dateEnd);//开始日期和结束日期验证
            if (timeCheck == 'exception') {
              //直接在这里发送http请求
              this.$emit('startCreateAct', {basicInfoFrom: this.form, finishStep: 1})
            }
          } else {
            return false;
          }
        });
      },
      NextStepEdit (form) { //编辑页面提交
        this.$refs[form].validate((valid) => {
          if (valid) {
            let timeCheck = this.compTime(this.form.dateStart, this.form.dateEnd);//开始日期和结束日期验证
            if (timeCheck == 'exception') {
                //直接在这里发送http请求
              this.$http.put('/api-active/v1/api/activityCenter/activity', this.form)
                .then((response) => {
                  let data = response.body;
                  if (data.resultCode == '200') {
                    postLog('ACTIVITY_LIST_EDIT', this.form.id, this.form.name, this.form);
                    this.$alert('修改成功', '提示');
                  } else {
                    this.$alert('修改失败', '提示');
                  }
                })
            }
          } else {
            alert('error submit!!');//表单验证不通过
            return false;
          }
        });
      },
      compTime (beginTime, endTime) { //开始时间结束时间对比
        let beginTimes = beginTime.substring(0, 10).split('-');
        let endTimes = endTime.substring(0, 10).split('-');
        beginTime = beginTimes[1] + '-' + beginTimes[2] + '-' + beginTimes[0] + ' ' + beginTime.substring(10, 19);
        endTime = endTimes[1] + '-' + endTimes[2] + '-' + endTimes[0] + ' ' + endTime.substring(10, 19);
        let a = (Date.parse(endTime) - Date.parse(beginTime)) / 3600 / 1000;
        if (a < 0) {
          this.$alert('开始时间不能大于结束时间', '提示');
        } else if (a > 0) {
          return 'exception'
        } else if (a == 0) {
          this.$alert('开始时间结束时间相等!', '提示');
        }
      },
      prev () {
        this.$emit('back', {showModules: 'type', active: 1});//导航进度条倒退一步
      }
    },
    created () {
      this.form.type = this.$store.state.actType.activityType;
      if (this.pageType == 'create' && this.$store.state.actType.modulesCount == 1) {
        this.createActivity = true;
      }
        // 如果发布了的产品就不能编辑
      if (this.pageType == 'edit' && this.$route.params.status == 1) {
        this.alreadyReleased = true;
      }
    }
  }
</script>

<style lang="less">
  .basicInfo{
    @greenStyle:#63c5ce;
    @orangeStyle:#f7931e;
     //公用按钮 上下步
    .buttonStep{
      width: 200px;
      border:0;
      background: @greenStyle;
      margin:30px 40px 0 40px;
      color:#fff;
    }
    .el-input.is-disabled .el-input__inner{
      background-color:#fff;
    }
    .el-textarea.is-disabled .el-textarea__inner{
      background: #fff;
    }
    .el-form-item__label{
      text-align: center;
    }
    .el-form-item__label:before{
      display:none;
      content: '';
    }
    .buttonStep{
      float: left;
      margin:0 30px;
      &:nth-child(1){
        margin-left:0;
      }
    }
    .el-form-item{
      margin-top:15px;
    }
    .actDateTime .el-form-item{
      margin-top: 0;
      margin-bottom: 7px;
    }
    .el-form .saveButton{
      margin-left:80px;
    }
    .el-upload__tip{
      display: inline-block;
      margin-left: 10px;
    }
  }
</style>
